package com.ruoyi.common.utils.ip

import com.alibaba.fastjson2.JSON
import com.ruoyi.common.constant.*
import com.ruoyi.common.utils.*
import com.ruoyi.common.utils.http.HttpUtils
import com.ruoyi.framework.config.RuoYiConfig
import org.slf4j.LoggerFactory

/**
 * 获取地址类
 *
 * @author ruoyi
 */
class AddressUtils {

    companion object {
        private val log = LoggerFactory.getLogger(AddressUtils.toString())

        // IP地址查询
        private const val IP_URL = "http://whois.pconline.com.cn/ipJson.jsp"

        // 未知地址
        private const val UNKNOWN = "XX XX"
        fun getRealAddressByIP(ip: String?): String {
            // 内网不查询
            if (IpUtils.internalIp(ip)) {
                return "内网IP"
            }
            if (RuoYiConfig.isAddressEnabled()) {
                try {
                    val rspStr = HttpUtils.sendGet(IP_URL, "ip=$ip&json=true", Constants.GBK)
                    if (StringUtils.isEmpty(rspStr)) {
                        log.error("获取地理位置异常 {}", ip)
                        return UNKNOWN
                    }
                    val obj = JSON.parseObject(rspStr)
                    val region = obj.getString("pro")
                    val city = obj.getString("city")
                    return "$region$city"
                } catch (e: Exception) {
                    log.error("获取地理位置异常 {}", ip)
                }
            }
            return UNKNOWN
        }
    }
}
